import request from "@/utils/request";

// 获取 sts 信息
export function getSTS() {
  return request({
    url: "pc/sts/get",
    method: "get",
  });
}

// 上传文件
export async function upload(data, onProgress) {
  let stsInfo = await getSTS();
  let key = `${stsInfo.data.dir}/${String(new Date().getTime())}_${
    data.file.name
  }`;
  let formData = new FormData();
  formData.append("success_action_status", "200");
  formData.append("policy", stsInfo.data.policy);
  formData.append("x-oss-signature", stsInfo.data.signature);
  formData.append("x-oss-signature-version", "OSS4-HMAC-SHA256");
  formData.append("x-oss-credential", stsInfo.data.x_oss_credential);
  formData.append("x-oss-date", stsInfo.data.x_oss_date);
  formData.append("key", key); // 文件名
  formData.append("x-oss-security-token", stsInfo.data.security_token);
  formData.append("file", data.file); // file 必须为最后一个表单域

  let result = await request({
    url: stsInfo.data.host,
    method: "post",
    data: formData,
    onUploadProgress: function (progressEvent) {
      let loaded = progressEvent.loaded;
      let total = progressEvent.total;
      let value = ((loaded / total) * 100).toFixed(0);
      onProgress(Number(value));
    },
  });
  return {
    data: { url: `${stsInfo.data.host}/${key}` },
    code: 20000,
  };
}
